﻿using System;
using Microsoft.Xna.Framework;

namespace PrisonStep
{
    public class ParticleEmitter
    {
        #region Member Variables

        private ParticleSystem mParticleSystem;

        private float mTimeBetweenParticles;

        private Vector3 mPreviousPosition;

        private float mTimeLeftOver;
        #endregion

        public ParticleEmitter(ParticleSystem aParticleSystem,
                               float aParticlesPerSecond, Vector3 aInitalPosition)
        {
            mParticleSystem = aParticleSystem;

            mTimeBetweenParticles = 1.0f / aParticlesPerSecond;

            mPreviousPosition = aInitalPosition;
        }

        public void Update(GameTime aGameTime, Vector3 aNewPosition)
        {
            float lDelta = (float)aGameTime.ElapsedGameTime.TotalSeconds;

            if (lDelta > 0)
            {
                Vector3 lVelocity = (aNewPosition - mPreviousPosition) / lDelta;

                float lTimeToSpend = mTimeLeftOver + lDelta;

                float lCurrentTime = -mTimeLeftOver;

                while (lTimeToSpend > mTimeBetweenParticles)
                {
                    lCurrentTime += mTimeBetweenParticles;

                    lTimeToSpend -= mTimeBetweenParticles;

                    float mu = lCurrentTime / lDelta;

                    Vector3 lPosition = Vector3.Lerp(mPreviousPosition, aNewPosition, mu);
                    
                        mParticleSystem.AddParticle(lPosition, lVelocity);
                }

                mTimeLeftOver = lTimeToSpend;
            }
            mPreviousPosition = aNewPosition;
        }
    }
}
